import 'dart:convert';

import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:oramemo/core/repositories/default_api.dart';
import 'package:oramemo/entity/base_entity.dart';
import 'package:oramemo/entity/custom_adjustemt_entity.dart';
import 'package:oramemo/entity/device_mine_entity.dart';
import 'package:oramemo/entity/requst/custom_model_post_entity.dart';
import 'package:oramemo/entity/requst/device_put_entity.dart';
import 'package:oramemo/pages/home/home_logic.dart';

class CustomAdjustmentLogic extends GetxController {
  final showTip1 = false.obs;
  final showTip2 = false.obs;
  final isEdit = false.obs;

  // 选择的耳朵
  final isRightEar = false.obs;

  // 各频率的增益值
  final freq250 = 0.obs;
  final freq500 = 0.obs;
  final freq1k = 0.obs;
  final freq2k = 0.obs;
  final freq3k = 0.obs;
  final freq4k = 0.obs;
  final freq6k = 0.obs;

  DeviceMineData? device = Get.arguments;

  CustomAdjustemtEntity entity = CustomAdjustemtEntity();

  // 添加历史记录和重做记录
  final List<Map<String, int>> _undoHistory = [];
  int _undoIndex = 0;

  // 添加撤销和重做状态
  final RxBool canUndo = false.obs;
  final RxBool canRedo = false.obs;

  @override
  void onInit() {
    load();
    _saveCurrentState();
    super.onInit();
  }

  // 选择耳朵
  void selectEar(bool ear) {
    if (isRightEar.value != ear) {
      // 保存当前耳朵的设置
      saveCurrentEarSettings();
      // 切换耳朵
      isRightEar.value = ear;
      // 加载对应耳朵的设置
      loadEarSettings(ear);
    }
  }

  // 设置频率值
  void setFrequencyValue(RxInt frequency, int value) {
    frequency.value = value;
  }

  // 保存当前所有频率值的状态
  void _saveCurrentState() {
    final currentState = {
      'isRightEar': isRightEar.value ? 1 : 0,
      'freq250': freq250.value,
      'freq500': freq500.value,
      'freq1k': freq1k.value,
      'freq2k': freq2k.value,
      'freq3k': freq3k.value,
      'freq4k': freq4k.value,
      'freq6k': freq6k.value,
    };
    _undoHistory.add(currentState);
    _undoIndex = _undoHistory.length - 1;
  }

  // 撤销操作
  void undo() {
    _undoIndex--;
    if (_undoIndex < 0) return;

    // 恢复上一个状态
    final previousState = _undoHistory[_undoIndex];

    // 恢复耳朵选择
    bool previousEar = previousState['isRightEar'] == 1;
    if (isRightEar.value != previousEar) {
      // 保存当前耳朵的设置
      saveCurrentEarSettings();
      // 切换到历史记录中的耳朵
      isRightEar.value = previousEar;
    }

    // 恢复频率值
    freq250.value = previousState['freq250'] ?? 0;
    freq500.value = previousState['freq500'] ?? 0;
    freq1k.value = previousState['freq1k'] ?? 0;
    freq2k.value = previousState['freq2k'] ?? 0;
    freq3k.value = previousState['freq3k'] ?? 0;
    freq4k.value = previousState['freq4k'] ?? 0;
    freq6k.value = previousState['freq6k'] ?? 0;

    // 更新状态
    canUndo.value = _undoIndex >= 1;
    canRedo.value = _undoHistory.length > _undoIndex + 1;
    update();
  }

  // 重做操作
  void redo() {
    _undoIndex++;
    if (_undoIndex >= _undoHistory.length) return;

    // 恢复下一个状态
    final nextState = _undoHistory[_undoIndex];

    // 恢复耳朵选择
    bool nextEar = nextState['isRightEar'] == 1;
    if (isRightEar.value != nextEar) {
      // 保存当前耳朵的设置
      saveCurrentEarSettings();
      // 切换到历史记录中的耳朵
      isRightEar.value = nextEar;
    }

    // 恢复频率值
    freq250.value = nextState['freq250'] ?? 0;
    freq500.value = nextState['freq500'] ?? 0;
    freq1k.value = nextState['freq1k'] ?? 0;
    freq2k.value = nextState['freq2k'] ?? 0;
    freq3k.value = nextState['freq3k'] ?? 0;
    freq4k.value = nextState['freq4k'] ?? 0;
    freq6k.value = nextState['freq6k'] ?? 0;

    // 更新状态
    canUndo.value = _undoIndex >= 1;
    canRedo.value = _undoHistory.length > _undoIndex + 1;
    update();
  }

  // 保存当前耳朵的设置到实体中
  void saveCurrentEarSettings() {
    if (isRightEar.value) {
      // 保存右耳设置
      entity.earr ??= CustomAdjustemtEarl();
      entity.earr!.f250 = freq250.value;
      entity.earr!.f500 = freq500.value;
      entity.earr!.f1k = freq1k.value;
      entity.earr!.f2k = freq2k.value;
      entity.earr!.f3k = freq3k.value;
      entity.earr!.f4k = freq4k.value;
      entity.earr!.f6k = freq6k.value;
    } else {
      // 保存左耳设置
      entity.earl ??= CustomAdjustemtEarl();
      entity.earl!.f250 = freq250.value;
      entity.earl!.f500 = freq500.value;
      entity.earl!.f1k = freq1k.value;
      entity.earl!.f2k = freq2k.value;
      entity.earl!.f3k = freq3k.value;
      entity.earl!.f4k = freq4k.value;
      entity.earl!.f6k = freq6k.value;
    }
  }

  // 设置频率值
  void putFrequencyValue(RxInt frequency, int value) {
    frequency.value = value;
    // 保存当前状态到历史记录
    _saveCurrentState();
    // 保存当前耳朵的设置
    saveCurrentEarSettings();

    canUndo.value = _undoHistory.isNotEmpty;
    update();
  }

  void setMasterEqualizer(CustomAdjustemtEarl data) {
    freq250.value = data.f250 ?? 0;
    freq500.value = data.f500 ?? 0;
    freq1k.value = data.f1k ?? 0;
    freq2k.value = data.f2k ?? 0;
    freq3k.value = data.f3k ?? 0;
    freq4k.value = data.f4k ?? 0;
    freq6k.value = data.f6k ?? 0;
  }

  void loadEarSettings(bool ear) {
    if (ear == false) {
      setMasterEqualizer(entity.earl!);
    } else {
      setMasterEqualizer(entity.earr!);
    }
  }

  void saveSettings() async {
    DevicePutEntity devicePutEntity = DevicePutEntity()
      ..id = device?.device?.id
      ..deviceConfig = entity.toString();
    final res = await DefaultApi()
        .oraDevicePut<BaseEntity>(entity: devicePutEntity, isShowLoading: true);
    
    final CustomModelPostEntity customModelPostEntity = CustomModelPostEntity()
      ..modelConfig = devicePutEntity.deviceConfig
      ..deviceId = devicePutEntity.id;
    DefaultApi().oraCustomModelPost<BaseEntity>(body: customModelPostEntity);

    if (res?.isSuccess == true) {
      HomeLogic.to.requestDevices();
      Toast.show('保存成功');
      Get.back(result: entity.toString());
    }
  }

  void load() {
    if (device?.device?.deviceConfig?.isNotEmpty == true) {
      final source = device!.device!.deviceConfig!;
      loadCustom(source);
    }
  }

  void loadCustom(String source) {
    try {
      entity = CustomAdjustemtEntity.fromJson(jsonDecode(source));
      loadEarSettings(isRightEar.value);
      update();
    } catch (e) {
      log(e.toString());
    }
  }
}
